import { fetchDropPartTypeList, fetchDropOrgAllList, fetchDropAllAccountList } from '@/api/common/commonDropDown'

const state = {
  dropPartTypeList: [], // 部件类型下拉
  accountCascadeList: [], // 用户级联数据
  dropOrgList: [] // 机构下拉
}

const mutations = {
  SET_DROP_LIST: (state, list) => { // 设置下拉数据
    Object.assign(state, list)
  }
}

const actions = {
  postDropPartTypeList({ commit }) { // 部件类型下拉
    fetchDropPartTypeList().then(res => {
      const dropPartTypeList = res.map(item => ({ key: item.id, value: item.typeName }))
      commit('SET_DROP_LIST', { dropPartTypeList })
    })
  },

  postDropOrgList({ commit }) { // 机构下拉
    fetchDropOrgAllList().then(res => {
      const dropOrgList = res.map(item => ({ key: item.id, value: item.orgName }))
      commit('SET_DROP_LIST', { dropOrgList })
    })
  },

  postAccountCascade({ commit }, orgId) { // 用户级联数据
    fetchDropAllAccountList({ orgId }).then(res => {
      const accountCascadeList = methods.formatAccountCascadeList(res)
      commit('SET_DROP_LIST', { accountCascadeList })
    })
  }
}

const methods = {
  formatAccountCascadeList(data) { // 格式化用户级联数据
    const deptIdList = []
    const accountCascadeList = []
    data.map(item => {
      const index = deptIdList.indexOf(item.deptId)
      if (!deptIdList.length || index < 0) {
        deptIdList.push(item.deptId)
        accountCascadeList.push({ value: item.deptId, label: item.deptName, children: [{ value: item.id, label: item.name }] })
      } else {
        accountCascadeList[index].children.push({ value: item.id, label: item.name })
      }
    })
    return accountCascadeList
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
